<?php

namespace App\Events;


use App\Master\Framework\Extend\Module;
use App\Master\Framework\Extend\Utils;

use App\Model\Framework\Sta\Visit;
use App\Service\GaoDeMapService;
use Illuminate\Broadcasting\InteractsWithSockets;

use Illuminate\Broadcasting\PrivateChannel;

use Illuminate\Foundation\Events\Dispatchable;

use Illuminate\Http\Request;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\DB;
use Jenssegers\Agent\Agent;


class HomeVisitEvent
{
    use Dispatchable, InteractsWithSockets, SerializesModels;
    
    
    /**
     * Create a new event instance.
     *
     * @param array $params
     * @return bool
     */
    public function __construct()
    {

        if(Request::capture ()->isMethod ('post'))
        {
            return true;
        }

        if (session_status() !== PHP_SESSION_ACTIVE) session_start();

        $key = session_id();

        session_destroy();
        
        $params['url'] = Request::capture ()->getUri ();
        $params['session_id'] = $key;
        $params['created_at'] = time ();
        $params['referer'] = $this->refererMap();
        $params['ip'] = Request::capture()->getClientIp();
        $params['browser'] = (new Agent())->browser();
        $params['region'] = (new GaoDeMapService)->IPLocation(Request::capture()->getClientIp()) ?: Utils::getIpRegion();
        $params['created_date'] = date('Y-m-d');
        $params['created_hour'] = date('H');
        Visit::insert($params);
    }

    public function refererMap()
    {
        $local_url = parse_url(Request::capture ()->getUri ());
        if(!isset($local_url['scheme']) || !isset($local_url['host']))
        {
            return '直接访问';
        }
        $referer = (parse_url(@$_SERVER['HTTP_REFERER']));
        if(!isset($referer['scheme']) || !isset($referer['host']))
        {
            return '直接访问';
        }
        if(($referer['scheme'].'://'. $referer['host']) == $local_url['scheme'].'://'. $local_url['host'])
        {
            return '直接访问';
        }
        return $referer['scheme'].'://'. $referer['host'];
    }
    
    /**
     * Get the channels the event should broadcast on.
     *
     * @return \Illuminate\Broadcasting\Channel|array
     */
    public function broadcastOn()
    {
        return new PrivateChannel('channel-name');
    }
}
